package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class GuliFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return template -> {
            //feign远程之前先执行拦截器方法requestInterceptor()
            //1.RequestContextHolder拿到request请求(通过threadLocal)
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                //2.同步请求头信息Cookie
                HttpServletRequest request = attributes.getRequest();
                String cookie = request.getHeader("Cookie");
                template.header("Cookie",cookie);
            }
        };
    }
}
